package tts.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import tts.dao.UsersHome;
import tts.model.Roles;
import tts.model.Users;

@SuppressWarnings("deprecation")
public class CustomUserServiceDetailsImpl implements UserDetailsService {

	//fields
	@Autowired
	private UsersHome usersHome;

	//methods
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException{
		Collection<GrantedAuthority> myGrantedAuthoritiesList = new HashSet<GrantedAuthority>();
		Users user = new Users();
		try {
			user = usersHome.findByUsername(username);
			if (user == null) throw new UsernameNotFoundException("user not found");
			if (user.isEnabled() == false) throw new UsernameNotFoundException("user not found");
			List<Roles> rolesList = user.getRolesList();
			List<String> rolesListString = new ArrayList<String>();
			for (Roles r : rolesList)
				rolesListString.add(r.getRoleName());
			for (String s : rolesListString)
				myGrantedAuthoritiesList.add(new GrantedAuthorityImpl(s));
		} catch (UsernameNotFoundException e) {
			throw e;
		} catch (Exception e) {
			throw e;
		} 
		return new CustomUserDetailsBean(username, user.getPassword(), true, true, true, true, myGrantedAuthoritiesList);
	}
}